namespace SB2.Core;
/// <summary>
/// 认证
/// </summary>
[Route("api/core/[Controller]")]
[ApiDescriptionSettings("core")]
public class AuthAppService : IDynamicApiController
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly UserRepository _userRepository;
    public AuthAppService(IHttpContextAccessor httpContextAccessor, UserRepository u)
    {
        _httpContextAccessor = httpContextAccessor;
        _userRepository = u;

    }
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<object> LoginAsync(UserLoginDto dto)
    {
        // 判断用户名和密码是否正确 
        var user = await _userRepository
            .GetFirstAsync(u => u.Name.Equals(dto.Name));
        if (user == null)
            throw Oops.Oh("用户不存在！");
        // 验证账号是否被冻结
        if (user.AdminStatus == AdminStatus.Disable)
            throw Oops.Oh("用户禁用！");
        if (!user.CheckePwd(dto.Pwd))
            throw Oops.Oh("密码不正确！");
        // // 员工信息
        // var empInfo = _sysEmpService.GetEmpInfo(user.Id).Result;

        // // 获取数据权限
        // var dataScopes = JsonUtil.ToJson(_sysUserService.GetUserDataScopeIdList(user.Id).Result);
        // 生成Token令牌

        var requestEncrypt = App.Configuration["RequestEncrypt"]; // 请求是否加密
        var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
            {
                {ClaimConst.CLAINM_USERID, user.UserID},
                {ClaimConst.REQUESTENCRYPT, requestEncrypt},
                // {ClaimConst.CLAINM_ACCOUNT, user.Name},
                // {ClaimConst.CLAINM_NAME, "管理员"},
                // {ClaimConst.CLAINM_SUPERADMIN, user.AdminType},
                // {ClaimConst.CLAINM_ORGID, empInfo.OrgId},
                // {ClaimConst.CLAINM_ORGNAME, empInfo.OrgName},
                // {ClaimConst.DATA_SCOPES, dataScopes}
            });

        // 设置Swagger自动登录
        _httpContextAccessor.HttpContext.SigninToSwagger(accessToken);

        // 生成刷新Token令牌
        var refreshToken =
            JWTEncryption.GenerateRefreshToken(accessToken, App.GetOptions<RefreshTokenSettingOptions>().ExpiredTime);

        // 设置刷新Token令牌
        _httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken;
        return new { accessToken, refreshToken };
    }
}